# Copyright (c) 2020 Kosaki Mezumona
# This cmake script is distributed under the MIT License.
# See LICENSE for more details.
cmake_minimum_required(VERSION 3.1)
project(quickjs)

option(BIGNUM "Enable big number support" ON)

set(quickjs_version 2021-03-27)
set(quickjs_url https://bellard.org/quickjs/quickjs-${quickjs_version}.tar.xz)
set(quickjs_sha1 95836721cf3931a0043461db6c710415f05ed2cf)
set(quickjs_extras_url https://bellard.org/quickjs/quickjs-extras-${quickjs_version}.tar.xz)
set(quickjs_extras_sha1 06b293cbbbd2b4f4a42f303ae5ff4cd71e0c9715)
set(quickjs_extract_dir ${CMAKE_CURRENT_BINARY_DIR}/sources)
set(quickjs_sources_root ${quickjs_extract_dir}/quickjs-${quickjs_version})
set(quickjs_sources
	${quickjs_sources_root}/quickjs.h
	${quickjs_sources_root}/quickjs-libc.h
	${quickjs_sources_root}/quickjs.c
	${quickjs_sources_root}/libregexp.c
	${quickjs_sources_root}/libunicode.c
	${quickjs_sources_root}/cutils.c
	${quickjs_sources_root}/quickjs-libc.c
)
set(quickjs_sources_qjsc
	${quickjs_sources_root}/qjsc.c
)

set(quickjs_sources_qjs
	${quickjs_sources_root}/qjs.c
)

set(quickjs_sources_bf
	${quickjs_sources_root}/libbf.c
)

set(get_quickjs_cmake_in ${CMAKE_CURRENT_LIST_DIR}/get_quickjs.cmake.in)
set(get_quickjs_cmake ${CMAKE_CURRENT_BINARY_DIR}/get_quickjs.cmake)
configure_file(
	${get_quickjs_cmake_in}
	${get_quickjs_cmake}
	@ONLY
)
add_custom_command(
	OUTPUT
		${quickjs_sources} ${quickjs_sources_bf} ${quickjs_sources_qjsc} ${quickjs_sources_qjs}
	DEPENDS
		${get_quickjs_cmake}
	COMMENT
		Get quickjs sources.
	COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/get_quickjs.cmake
)

add_definitions(
	-DCONFIG_VERSION="${quickjs_version}"
	-D_GNU_SOURCE
)
if(BIGNUM)
	add_definitions(
		-DCONFIG_BIGNUM
	)
	set(quickjs_sources ${quickjs_sources} ${quickjs_sources_bf})
endif(BIGNUM)

add_library(${PROJECT_NAME}
	${quickjs_sources}
)
# set library include path
target_include_directories(${PROJECT_NAME} PUBLIC
	${quickjs_sources_root}
)

#qjsc compiler executable
add_executable(qjsc
	${quickjs_sources_qjsc}
)
target_link_libraries(qjsc
	${PROJECT_NAME}
	m
	dl
	pthread
)

set(quickjs_source_repl ${CMAKE_BINARY_DIR}/repl.c)
add_custom_command(
	OUTPUT
		${quickjs_source_repl}
	DEPENDS
		qjsc
	COMMENT
		compile repl.js and generate repl.c
	COMMAND qjsc ${quickjs_sources_root}/repl.js -c -m -o ${quickjs_source_repl}
)

if(${BIGNUM})
	#compile qjscalc.js
	set(quickjs_source_qjscalc ${CMAKE_BINARY_DIR}/qjscalc.c)
	add_custom_command(
		OUTPUT
			${quickjs_source_qjscalc}
		DEPENDS
			qjsc
		COMMENT
			compile qjscalc.js, generate qjscalc.c
		COMMAND qjsc ${quickjs_sources_root}/qjscalc.js -fbignum -c -o ${quickjs_source_qjscalc}
	)
else()
	set(quickjs_source_qjscalc "")
endif(${BIGNUM})

add_executable(qjs
	${quickjs_sources_qjs}
	${quickjs_source_repl}
	${quickjs_source_qjscalc}
)

target_link_libraries(qjs
	${PROJECT_NAME}
	m
	dl
	pthread
)